import KeyValuePairsDb, { KVPair, OperableStoreShow, ResultStatueCodeToText } from "../../logic/database/KeyValuePairsDb";
import Dialog, { DialogStatic, OptionGenerate_BaiscEditSaveDialog } from "../../logic/page/dialog";
import moment = require("moment");
import GetConfigJSON from "../../logic/network/config";

/** 时间格式 yyyy-MM-dd hh:mm:ss */
const MOMENT_TIME_FORMAT = "YYYY-MM-DD HH:mm:ss";

const db = new KeyValuePairsDb();

/** 完成计划记录 */
export interface ComplatePlanRecord {
    /** 计划ID */
    PlanID: string;
    /** 完成的步骤序号 */
    StepNo: number;
    /** 完成时间 (格式: yyyy-MM-dd hh:mm:ss) */
    Time: string;
    /** 完成备注 */
    Remark: string;
}

const edit_page_style = {
    width: "450px",
    height: "600px",
    padding: "10px 20px 0",
};

/**
 * 添加一个新的计划
 * @param store 数据操作区
 * @param plan_id 计划ID标识
 * @param stepNo 完成的步骤序号
 * @param callback 执行回调
 */
async function AddAsync(
    store: OperableStoreShow,
    plan_id: string,
    stepNo: number,
    callback?: (model: ComplatePlanRecord) => void
) {
    let config = await GetConfigJSON();
    let edit_page_url = `${config.BaseUrl}/functions/plan/complate_record.html`;
    let option: OptionGenerate_BaiscEditSaveDialog = {
        title: "完成一次计划",
        style: edit_page_style,
        url: edit_page_url,
        loadFunc: function (dialog: Dialog) {
            let form = dialog.GetDialog().find("form");
            form.form("load", {
                PlanID: plan_id,
                StepNo: stepNo,
            } as ComplatePlanRecord);
        },
        isSave: true,
        saveFunc: function (dialog: Dialog) {
            SaveAsync(store, dialog, callback);
        },
    };
    DialogStatic.ToGenerate_BaiscEditSaveDialog(option).Create().Open();
}

let EditLock_Save: boolean = false;
async function SaveAsync(store: OperableStoreShow, dialog: Dialog, callback?: (model: ComplatePlanRecord) => void) {
    var form = dialog.GetDialog().find("form");
    form.form("submit", {
        onSubmit: function () {
            $(this).form("enableValidation");
            return false;
        },
    });
    if (!form.form("validate")) {
        return;
    }
    var model = form.serializeJSON() as ComplatePlanRecord;
    if (!model.Time) {
        model.Time = moment().format(MOMENT_TIME_FORMAT);
    }

    if (EditLock_Save) {
        console.info("正在保存编辑内容, 锁定中...");
        return;
    }
    $.messager.progress({
        noheader: true,
        title: false,
        msg: "正在保存中...",
        interval: 100,
    });
    EditLock_Save = true;

    let db_key = `plan:complaterecord:${model.PlanID}:${model.StepNo}`;
    let dict: KVPair = {};
    dict[db_key] = model;

    let result = await db.Write(store.Name, dict);
    EditLock_Save = false;
    $.messager.progress("close");

    if (result.Code !== 0) {
        $.messager.alert({
            title: `错误: ${ResultStatueCodeToText(result.Code)}`,
            msg: `保存计划完成记录出错, 消息: ${result.Message}`,
            icon: "error",
        });
        return;
    }
    let success_count = result.Data;
    if (success_count !== 1) {
        $.messager.alert({
            title: `结果警告`,
            msg: `保存计划完成记录结束, 但是返回成功数量不一致为: ${success_count}`,
            icon: "error",
        });
        return;
    }

    $.messager.alert({
        title: "提示",
        msg: "保存成功",
        icon: "success",
    });
    dialog.Close();
    if (callback) {
        callback(model);
    }
}

/**
 * 查询完成计划记录队列
 * @param store 数据操作区
 * @param plan_id 计划ID标识
 * @returns 完成计划记录队列
 */
async function QueryComplatePlanRecords(store: OperableStoreShow, plan_id: string): Promise<ComplatePlanRecord[]> {
    let db_key = `plan:complaterecord:${plan_id}:/(\\d+)/i`;
    let result = await db.Read(store.Name, db_key);
    if (result.Code !== 0) {
        console.error(`错误: ${ResultStatueCodeToText(result.Code)}`);
        console.error(`读取完成记录错误, 消息: ${result.Message}`);
        return [];
    }
    let dict: KVPair = result.Data;
    return ToValues<ComplatePlanRecord>(dict);
}

function ToValues<T>(dict: KVPair): T[] {
    let arr = [];
    if (!dict) return arr;
    for (const key in dict) {
        arr.push(dict[key]);
    }
    return arr;
}

export default {
    Add: AddAsync,
    Querys: QueryComplatePlanRecords,
};
